<?php

namespace app\admin\controller;

use app\common\controller\Backend;
use think\Db;
use think\Response;

/**
 * 电梯管理
 *
 * @icon fa fa-circle-o
 */
class Corporation extends Backend
{

    /**
     * Corporation模型对象
     * @var \app\admin\model\Corporation
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\Corporation;

    }



    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */


    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = false;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $list = $this->model
                    
                    ->where($where)
                    ->order($sort, $order)
                    ->paginate($limit);

            foreach ($list as $row) {
                $row->visible(['id','name','region','present','phone','code','remarks','qrcode_url','expiration_date','audit']);
                
            }

            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch();
    }
     /**
     * 添加
     *
     * @return string
     * @throws \think\Exception
     */
    public function add()
    {
        if (false === $this->request->isPost()) {
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        $params['qrcode_value']=md5($params['name'].$params['present'] . time());
        $code_img_data = $_SERVER['REQUEST_SCHEME'] . '://' . $_SERVER['HTTP_HOST'] . '/index/qrcode/index?code=' . $params['qrcode_value'] . '&type=3';
        $params['qrcode_url']=$this->build($code_img_data);
        // var_dump($params);die();
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);
         // var_dump($params);die();
        if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
            $params[$this->dataLimitField] = $this->auth->id;
        }
        $result = false;
        Db::startTrans();
        try {
            //是否采用模型验证
            if ($this->modelValidate) {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                $this->model->validateFailException()->validate($validate);
            }
            $result = $this->model->allowField(true)->save($params);
            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($result === false) {
            $this->error(__('No rows were inserted'));
        }
        $this->success();
    }
    // 生成二维码
    public function build($code)
    {
        $config = get_addon_config('qrcode');
        if (isset($config['limitreferer']) && $config['limitreferer']) {
            $referer = $this->request->server('HTTP_REFERER', '');
            $refererInfo = parse_url($referer);
            $refererHost = $referer && $refererInfo ? $refererInfo['host'] : '';
            $refererHostArr = explode('.', $refererHost);
            $wildcardDomain = '';
            if (count($refererHostArr) > 2) {
                $refererHostArr[0] = '*';
                $wildcardDomain = implode('.', $refererHostArr);
            }
            $allowRefererList = $config['allowrefererlist'] ?? '';
            $domainArr = explode("\n", str_replace("\r", "", $allowRefererList));
            $domainArr = array_filter(array_unique($domainArr));
            $domainArr[] = request()->host(true);

            $inAllowList = false;

            if (in_array('*', $domainArr) || ($refererHost && in_array($refererHost, $domainArr)) || ($wildcardDomain && in_array($wildcardDomain, $domainArr))) {
                $inAllowList = true;
            }

            if (!$inAllowList && (!$referer && $config['allowemptyreferer'])) {
                $inAllowList = true;
            }

            if (!$inAllowList) {
                $response = Response::create('暂无权限', 'html', 403);
                throw new HttpResponseException($response);
            }
        }
        $params = $this->request->get();
        $params = array_intersect_key($params, array_flip(['text', 'size', 'padding', 'errorlevel', 'foreground', 'background', 'logo', 'logosize', 'logopath', 'label', 'labelfontsize', 'labelalignment']));
        //原有$config['text'] 为二维码码值，通过配置获取
        // $params['text'] = $this->request->get('text', $config['text'], 'trim');
        
        $params['text'] = $this->request->get('text', $code, 'trim');
        $params['label'] = $this->request->get('label', $config['label'], 'trim');

        $qrCode = \addons\qrcode\library\Service::qrcode($params);
                // var_dump($qrCode);die();
        $mimetype = $config['format'] == 'png' ? 'image/png' : 'image/svg+xml';

        // var_dump(Response::create()->header("Content-Type", $mimetype));die();

        $response = Response::create()->header("Content-Type", $mimetype);

        // // 直接显示二维码
        // header('Content-Type: ' . $qrCode->getContentType());
        // $response->content($qrCode->writeString());

        // 写入到文件
        // var_dump($config['writefile']);die();
        if ($config['writefile']) {
             // var_dump($config['writefile']);die();
            $qrcodePath = ROOT_PATH . 'public/uploads/qrcodeurl/';
            if (!is_dir($qrcodePath)) {
                @mkdir($qrcodePath);
            }
            if (is_really_writable($qrcodePath)) {
                $filePath = $qrcodePath . md5(implode('', $params)) . '.' . $config['format'];
                $qrCode->writeFile($filePath);
                $qrcodevalue = substr($filePath, strpos($filePath, "uploads") - 1);
            }
        }
        // var_dump($qrcodevalue);
        return $qrcodevalue;
    }

}
